package pers.zhouyoudianxi.notice2.serviceImpl;

import com.alibaba.fastjson.JSONArray;
import pers.zhouyoudianxi.notice2.bean.Notice;
import pers.zhouyoudianxi.notice2.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;

import static pers.zhouyoudianxi.notice2.config.DynamicCronTask.NOTICE_LIST;
import static pers.zhouyoudianxi.notice2.config.DynamicCronTask.removeControlChars;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Value("${file.path}")
    String filePath;
    private static String DEF_CONFIG = "";

    static {
        DEF_CONFIG = "[{\n" +
                "\t\"id\": 1,\n" +
                "\t\"cron\": \"0 0/30 * * * ?\",\n" +
                "\t\"title\": \"每半小时提醒一次\",\n" +
                "\t\"detail\": \"提醒内容，30为每小时内每隔几分钟提醒一次，默认open为0不开启\",\n" +
                "\t\"open\": 0\n" +
                "}, {\n" +
                "\t\"id\": 2,\n" +
                "\t\"cron\": \"0 0 * * * ?\",\n" +
                "\t\"title\": \"每个整点提醒一次\",\n" +
                "\t\"detail\": \"提醒内容，默认open为0不开启\",\n" +
                "\t\"open\": 0\n" +
                "}, {\n" +
                "\t\"id\": 3,\n" +
                "\t\"cron\": \"0 0 14 * * ?\",\n" +
                "\t\"title\": \"每天的14时提醒一次\",\n" +
                "\t\"detail\": \"提醒内容，最前边为秒，第二位为分钟，可以指定某个时刻提醒，默认open为0不开启\",\n" +
                "\t\"open\": 0\n" +
                "}, {\n" +
                "\t\"id\": 4,\n" +
                "\t\"cron\": \"5 * * * * ?\",\n" +
                "\t\"title\": \"测试项目\",\n" +
                "\t\"detail\": \"默认每分钟弹窗一次，修改配置文件后可以自行关闭，配置文件后缀.json  数据格式遵循json数据格式\",\n" +
                "\t\"open\": 0\n" +
                "}]";
    }

    @Override
    public boolean initConfig() {
        log.info("初始化配置文件中");
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
                // try-with-resources语法，自动关闭资源
                try (Writer writer = new OutputStreamWriter(new FileOutputStream(file),
                        StandardCharsets.UTF_8)) {
                    // 写入内容
                    writer.write(DEF_CONFIG);
                    log.info("文件写入成功");
                } catch (IOException e) {
                    log.error("文件写入失败: " + e.getMessage());
                }
                NOTICE_LIST = JSONArray.parseArray(removeControlChars(DEF_CONFIG), Notice.class);
                log.info("初始化配置文件成功");
            } else {
                log.info("配置文件已存在");
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.info("初始化配置文件失敗");
        return false;
    }

    @Override
    public boolean readConfig() {
        log.info("读取配置文件中");
        StringBuffer stringBuffer = new StringBuffer();
        // try-with-resources 自动关闭资源
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            // 按行读取
            while ((line = br.readLine()) != null) {
                stringBuffer.append(line);
            }
            NOTICE_LIST = JSONArray.parseArray(removeControlChars(stringBuffer.toString()), Notice.class);
            log.info("读取配置文件成功");
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.info("读取配置文件失敗");
        return false;
    }

    @Override
    public boolean writeConfig() {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                // try-with-resources语法，自动关闭资源
                try (Writer writer = new OutputStreamWriter(new FileOutputStream(file),
                        StandardCharsets.UTF_8)) {
                    // 写入内容
                    writer.write(convertList2FileString());
                    log.info("文件写入成功");
                } catch (IOException e) {
                    log.error("文件写入失败: " + e.getMessage());
                }
                log.info("初始化配置文件成功");
            } else {
                log.info("配置文件不存在");
            }
        } catch (Exception e) {
            log.error("写入配置文件失败：{}", e.getMessage());
        }
        return false;
    }

    private String convertList2FileString() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");
        Notice notice;
        for (int i = 0; i < NOTICE_LIST.size(); i++) {
            notice = NOTICE_LIST.get(i);
            stringBuffer.append("{\n");
            stringBuffer.append("\t\"id\":  " + notice.getId() + ",\n");
            stringBuffer.append("\t\"cron\":  \"" + notice.getCron() + "\",\n");
            stringBuffer.append("\t\"title\":  \"" + notice.getTitle() + "\",\n");
            stringBuffer.append("\t\"detail\":  \"" + notice.getDetail() + "\",\n");
            stringBuffer.append("\t\"open\": " + notice.getOpen() + "\n");
            stringBuffer.append("}");
            if (i != NOTICE_LIST.size() - 1) {
                stringBuffer.append(",");
            }
        }
        stringBuffer.append("]");
        return stringBuffer.toString();

    }

}
